package conu.mapmaker.area;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import conu.mapmaker.display.DisplayInterface;

import javax.swing.JPanel;

/**
 * City holds grid of Areas
 * 
 * @author FLiP
 * 
 */

public class City extends JPanel implements DisplayInterface, AreaInterface {

	int cityWidthMetres, cityHeightMetres, cityWidthPixels, cityHeightPixels;
	private Sector[][] sectors;
	private double MPP = 1;
	private int xOffset = 0, yOffset = 0;
	int sectorsWide, sectorsHigh;
	private Sector previousSector = (Sector) null;

	/**
	 * 
	 * @param width
	 *            in meters
	 * @param height
	 *            in meters
	 */
	public City(int width, int height) {
		sectorsWide = width;
		sectorsHigh = height;

		cityWidthMetres = width * SECTOR_WIDTH_M;
		cityHeightMetres = height * SECTOR_HEIGHT_M;

		pixelPerMetre();
		offset();

		cityWidthPixels = (int) (cityWidthMetres / MPP);
		cityHeightPixels = (int) (cityHeightMetres / MPP);

		this.setPreferredSize(new Dimension(cityWidthPixels, cityHeightPixels));
		System.out.println(this.getPreferredSize());
		this.setBackground(Color.black);

		generateSectorGrid();
	}

	private void generateSectorGrid() {
		System.out.println(sectorsWide + " " + sectorsHigh);
		sectors = new Sector[sectorsWide][sectorsHigh];

		// Sector placement in pixels
		for (int i = 0; i < sectors.length; i++) {
			for (int j = 0; j < sectors[0].length; j++) {
				sectors[i][j] = new Sector((int) (i * SECTOR_WIDTH_M / MPP), (int) (j * SECTOR_HEIGHT_M / MPP), MPP);
			}
		}

	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		for (int i = 0; i < sectorsWide; i++) {
			for (int j = 0; j < sectorsHigh; j++) {
				sectors[i][j].paintComponent(g);
			}
		}
	}

	// getter for sector array
	public Sector[][] getSectors() {
		return sectors;
	}

	// getter for the x-offset
	public int getXOffset() {
		return xOffset;
	}

	// getter for the y-offset
	public int getYOffset() {
		return yOffset;
	}

	// pixel per metre calculation for display
	private void pixelPerMetre() {
		MPP = Math.max(cityHeightMetres, cityWidthMetres) / (FRAME_DIM * 1.0);
	}

	// offset calculation for centering
	private void offset() {
		if (cityHeightMetres > cityWidthMetres) {
			// X is offset
			xOffset = (DisplayInterface.FRAME_DIM - (int) (cityWidthMetres / MPP)) / 2;
		} else if (cityHeightMetres < cityWidthMetres) {
			// Y is offset
			yOffset = (DisplayInterface.FRAME_DIM - (int) (cityHeightMetres / MPP)) / 2;
		}
	}

	public void detectSector(int x, int y) {
		int sectX, sectY;
		if (previousSector != (Sector) null)
			previousSector.setSelected(false);
		sectX = (int) Math.floor(x / (SECTOR_WIDTH_M / MPP));
		sectY = (int) Math.floor(y / (SECTOR_HEIGHT_M / MPP));
		sectors[sectX][sectY].setSelected(true);
		previousSector = sectors[sectX][sectY];
		repaint();

		//System.out.printf("(%d,%d) is located in Sector(%d,%d)\n", x, y, sectX, sectY);
	}
}
